﻿var wrapper = {};

//设置
wrapper.settings = {
    homeTabTitle: '我的桌面',
    homeTabUrl: '/undetermined',//待定
    maxTabCount: 10,
    origHeight: 0,
    iframe: "<iframe id='我的桌面' src='Mydesk.aspx' style='width:100%;height:100%;overflow: hidden;border:none'></iframe>",

};

//初始化
wrapper.init = function () {
    com.ajax({ type: 'POST', url: '/Logic/BD/IndexAjax.aspx', success: wrapper.initMenu, data: { method: "GetPerTree" } });

    $('.loginOut').click(wrapper.logout);
    $('.changepwd').click(wrapper.changePassword);
    $('.shortCut').click(wrapper.setShortCut);
    $('.changeSkin').click(wrapper.ChangeSki);
    $('.waitDeal').click(wrapper.waitDeal);
    $('.myMessage').click(wrapper.myMessageList);
    $('.myAuthor').click(wrapper.myAuthorList);
    $('#tabs').tabs({
        tools: [{ iconCls: 'icon-screen_full', handler: wrapper.setFullScreen },
                { iconCls: 'panel-tool-close', handler: wrapper.tabClose }],
        onContextMenu: wrapper.tabContextMenu,
        onClose: wrapper.setLocationHash,
        onSelect: wrapper.setLocationHash
    });

    $("#divMsg").dialog({
        title: '我的消息',
        width: 655,
        height: 400,
        closed: true,
        cache: false,
    });

    $("#aMsgUrl").click(function () {
        var msgUrl = $(this).attr("msgUrl");
        var msgTitle = $(this).attr("msgTitle");
        if (msgUrl != null && msgUrl != "") {
            wrapper.addTab(msgTitle, msgUrl);
        }
    });
    //  wrapper.getNotReadMsgCount();
    //先注释每隔5秒发送ajax


};





//事件
wrapper.tabContextMenu = function (e, title) {
    $('#closeMenu').menu('show', { left: e.pageX, top: e.pageY });
    $('#tabs').tabs('select', title);
    e.preventDefault();
};

wrapper.setShortCut = function () {
    $.extend(com.dialogObj, { title: "&nbsp;快速导航设置", width: 580, height: 400, href: "/UI/BD/SetShortCutWindow.aspx" })
    $("#divChangePwd").dialog(
       com.dialogObj
       )
}

wrapper.waitDeal = function () {
    $.extend(com.dialogObj, { title: "&nbsp;待办事宜设置", width: 580, height: 400, href: "/UI/BD/SetWaitDealWindow.aspx" })
    $("#divChangePwd").dialog(
       com.dialogObj
       )
}

wrapper.changePassword = function () {

    $.extend(com.dialogObj, { title: "&nbsp;修改密码", width: 320, height: 230, href: "/UI/BD/ChangePwdWindow1.aspx" })
    $("#divChangePwd").dialog(
       com.dialogObj
    );
};

wrapper.myMessageList = function () {
    wrapper.addTab("我的消息", "/UI/BD/MessagMyList.aspx");
}
wrapper.myAuthorList = function () {

    wrapper.addTab("我的授权", "/UI/BD/AuthorMyList.aspx");
}

wrapper.OpenMsgDialog = function () {
    $("#divMsg").dialog("open");
    $("#tbMsgList").datagrid({
        url: '/Logic/BD/UserAjax.aspx?method=GetPerWaitMsg',
        loadMsg: '数据加载中请稍后……',
        fitColumns: true,
        idField: "ID",
        singleSelect: true,
        striped: true,
        pageSize: 12,
        columns: [[
              {
                  field: 'Title', title: '', align: "center", width: 100, formatter: function (value, row, index) {
                      if (row.State == "1") {
                          return value;
                      } else {
                          return "<strong>" + value + "</strong>"
                      }
                  }
              },
        ]],
        onClickRow: function (rowIndex, rowData) {
            $("#msgH2").html(rowData.Title);
            $("#spnMsgFromName").html(rowData.FromName);
            $("#spnMsgTime").html(rowData.FillTime);
            $("#divMsgContent").html(rowData.Content);
            if (rowData.Url != null && rowData.Url != "") {
                $("#divMsgUrl").show();
                $("#aMsgUrl").attr("msgUrl", rowData.Url);
                $("#aMsgUrl").attr("msgTitle", rowData.Title);
            }
            else {
                $("#divMsgUrl").hide()
            }
            $("#divMsgRight").show();
            if (rowData.State == "1") {

            }
            else {
                $.ajax({
                    url: "/Logic/BD/UserAjax.aspx?method=MarkAsHaveRead",
                    type: "post",
                    data: { Id: rowData.ID },
                    dataType: "json",
                    success: function (data) {
                        if (data.state == "success") {
                            var content = $($("#divMsg tr")[rowIndex + 1]).find("strong").html();
                            $($("#divMsg tr")[rowIndex + 1]).find("strong").replaceWith(content);
                        }
                    }
                });
            }
        }
    });
}

wrapper.ChangeSki = function () {

    var className = $(this).attr("cookieValue");
    $.cookie('theme', className, { expires: 365 });
    com.message("success", "换肤成功，请按F5刷新页面");
    //  event.stopPropagation();
};


wrapper.setLocationHash = function () {
    try {
        var $obj = $('#tabs');
        var src = '', tabs = $obj.data().tabs.tabs;
        var tab = $obj.tabs('getSelected');

        var fnSrc = function (tab) {
            var iframe = tab.find('iframe');
            return iframe.length ? iframe[0].src.replace(location.host, '').replace('http://', '').replace('.aspx', '') : '';
        };

        if (tab) {
            src = fnSrc(tab);
            if (src) window.location.hash = '!' + src;   //如果src没有，就不设置，case在f5刷新时出现
            if (src == homeUrl) window.location.hash = '';
        }
        else {
            src = fnSrc(tabs[tabs.length - 1]); //关闭tabs时，当前tab为空
            window.location.hash = '!' + src;
        }
    }
    catch (e) { }
}



wrapper.logout = function () {
    $.messager.confirm('系统提示', '您确定要退出本次登录吗?', function (r) {
        if (r) location.href = '/Login.aspx';
    });
};
//重新计算Iframe里面的母版的高度，并赋值
wrapper.reSetContentHeight = function () {

    var $tab = $('#tabs');
    var currentTab = $tab.tabs('getSelected');
    var title = currentTab.panel('options').title;

    $inner = $(document.getElementById(title).contentWindow.document);
    var height = $inner.find("#divTotal").height();
    var content = parseFloat(height) - 40
    $inner.find("#divContent").css("height", content);
}

wrapper.getContentHeight = function () {
    var $tab = $('#tabs');
    var currentTab = $tab.tabs('getSelected');
    var title = currentTab.panel('options').title;

    $inner = $(document.getElementById(title).contentWindow.document);
    var height = $inner.find("#divContent").height();
    wrapper.settings.origHeight = height;
}

wrapper.setFullScreen = function () {

    var that = $(this);
    if (that.find('.icon-screen_full').length) {
        that.find('.icon-screen_full').removeClass('icon-screen_full').addClass('icon-screen_actual');
        wrapper.getContentHeight();
        $("#layout").layout("collapse", "north");
        $("#layout").layout("collapse", "west")

        wrapper.reSetContentHeight();

    } else if ($(this).find('.icon-screen_actual').length) {
        that.find('.icon-screen_actual').removeClass('icon-screen_actual').addClass('icon-screen_full');
        $("#layout").layout("expand", "north");
        $("#layout").layout("expand", "west");
        var $tab = $('#tabs');
        var currentTab = $tab.tabs('getSelected');
        var title = currentTab.panel('options').title;
        $inner = $(document.getElementById(title).contentWindow.document);

        $inner.find("#divContent").css("height", wrapper.settings.origHeight);
    }

};

wrapper.rightMenuClick = function (item) {
    var $tab = $('#tabs');
    var currentTab = $tab.tabs('getSelected');
    var titles = wrapper.getTabTitles($tab);
    switch (item.id) {
        case "refresh":
            var src = $(currentTab.panel('options').content).attr('src');
            $tab.tabs('update', { tab: currentTab, options: { content: wrapper.createFrame(src) } });
            break;
        case "close":
            var currtab_title = currentTab.panel('options').title;
            $tab.tabs('close', currtab_title);
            break;
        case "closeall":
            $.each(titles, function () {
                if (this != wrapper.settings.homeTabTitle)
                    $tab.tabs('close', this);
            });
            break;
        case "closeother":
            var currtab_title = currentTab.panel('options').title;
            $.each(titles, function () {
                if (this != currtab_title && this != wrapper.settings.homeTabTitle)
                    $tab.tabs('close', this);
            });
            break;
        case "closeright":
            var tabIndex = $tab.tabs('getTabIndex', currentTab);
            if (tabIndex == titles.length - 1) {
                alert('亲，后边没有啦 ^@^!!');
                return false;
            }
            $.each(titles, function (i) {
                if (i > tabIndex && this != wrapper.settings.homeTabTitle)
                    $tab.tabs('close', this);
            });

            break;
        case "closeleft":
            var tabIndex = $tab.tabs('getTabIndex', currentTab);
            if (tabIndex == 1) {
                alert('亲，前边那个上头有人，咱惹不起哦。 ^@^!!');
                return false;
            }
            $.each(titles, function (i) {
                if (i < tabIndex && this != wrapper.settings.homeTabTitle)
                    $tab.tabs('close', this);
            });
            break;
        case "exit":
            $('#closeMenu').menu('hide');
            break;
        case "closeleftone":
            var tabIndex = $tab.tabs('getTabIndex', currentTab);
            if (tabIndex == 1) {
                // alert('大哥，悠着点，咱上头没人啊，不能太嚣张');
                return false;
            }
            var leftone = tabIndex - 1;
            $tab.tabs('close', leftone);
            break;
        case "closeCurrentrefreshleft":
            var tabIndex = $tab.tabs('getTabIndex', currentTab);
            if (tabIndex == 1) {
                return false;
            }
            var leftone = tabIndex - 1;
            leftonetab = $tab.tabs('getTab', leftone);
            var srcleft = $(leftonetab.panel('options').content).attr('src');
            $tab.tabs('update', {
                tab: leftonetab, options: {
                    content: wrapper.createFrame(srcleft),

                }
            });
            $tab.tabs('close', tabIndex);
            break;
    }

};

//方法
wrapper.initSettings = function (settings) {
    wrapper.settings = $.extend(wrapper.settings, settings);
};

wrapper.initMenu = function (d) {
    if (!d || !d.length) {
        $.messager.alert("系统提示", "<font color=red><b>您没有任何权限！请联系管理员。</b></font>", "warning", function () { location.href = '/Login.aspx'; });
        return;
    }
    $('body').data('menulist', d);
    wrapper.menuTree(d);
    // $("#home").html(wrapper.createFrame(wrapper.settings.homeTabUrl));
};


wrapper.tabClose = function () {
    if (confirm('确认要关闭所有窗口吗？'))
        wrapper.rightMenuClick({ id: 'closeall' });
};
wrapper.tabCurrentClose = function () {
    wrapper.rightMenuClick({ id: 'close' });
}


//关闭当前，更新制定tab
wrapper.tabClosethisRefreshByTitle = function (title) {
    var $tab = $("#tabs");
    var thatTab = $tab.tabs("getTab", title);
    if (thatTab != null) {
        var src = $(thatTab.panel('options').content).attr('src');
        if (typeof src === 'string');
        $tab.tabs('update', { tab: thatTab, options: { content: wrapper.createFrame(src) } })
    }
    var currentTab = $tab.tabs('getSelected');
    var currtab_title = currentTab.panel('options').title;
    $tab.tabs('close', currtab_title);
}

wrapper.createFrame = function (url, text) {
    var ifrStr = "<iframe id='" + text + "' src='" + url + "' style='width:100%;height:99%;overflow: visible;border:none'></iframe>";
    return ifrStr;
}

//更新指定tab
wrapper.tabRefreshByTitle = function (title) {
    var $tab = $("#tabs");
    var thatTab = $tab.tabs("getTab", title);
    var tabselected = $tab.tabs("select", title);
    if (thatTab != null) {
        var src = $(thatTab.panel('options').content).attr('src');
        if (typeof src === 'string');
        $tab.tabs('update', { tab: thatTab, options: { content: wrapper.createFrame(src) } })
    }
}

wrapper.openTabHandler = function ($tab, hasTab, subtitle, url) {
    if (!hasTab) {
        $tab.tabs('add', { title: subtitle, content: wrapper.createFrame(url, subtitle), closable: true, tools: [{ iconCls: 'icon-mini-refresh', handler: function () { $tab.tabs('select', subtitle); wrapper.tabRefresh(url); } }] });
    } else {
        $tab.tabs('select', subtitle);
        wrapper.tabRefresh(url);   //选择TAB时刷新页面
    }
};

wrapper.tabRefresh = function (url) {
    var $tab = $("#tabs");
    var currentTab = $tab.tabs('getSelected');
    var src = $(currentTab.panel('options').content).attr('src');
    if (typeof src === 'string') src = url;
    $tab.tabs('update', { tab: currentTab, options: { content: wrapper.createFrame(src) } })
};

wrapper.getTabTitles = function ($tab) {
    var titles = [];
    var tabs = $tab.tabs('tabs');
    $.each(tabs, function () { titles.push($(this).panel('options').title); });
    return titles;
};

wrapper.addTab = function (subtitle, url) {
    if (!url || url == '#') return false;
    var $tab = $('#tabs');
    var tabCount = $tab.tabs('tabs').length;

    var hasTab = $tab.tabs('exists', subtitle);
    if ((tabCount <= wrapper.settings.maxTabCount) || hasTab) {
        wrapper.openTabHandler($tab, hasTab, subtitle, url);
    }
    else
        $.messager.confirm("系统提示", '<b>您当前打开了太多的页面，如果继续打开，会造成程序运行缓慢，无法流畅操作！</b>', function (b) {
            if (b)
                wrapper.openTabHandler($tab, hasTab, subtitle, url);
        });
};



wrapper.menuTree = function (menus) {
    console.log(menus)
    //1.加载菜单树
    $("#menuTree").tree({
        data: menus,
        onClick: function (node) {
            if (!node.attributes.url || node.attributes.url == '#') {

                $("#menuTree").tree("toggle", node.target);
            }
            else {
                wrapper.addTab(node.text, node.attributes.url);
            }

        }, lines: true
    });
};

$(wrapper.init);